﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Microsoft.IdentityModel.Tokens;
using SmartWMS.Domain.SystemSet;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace SmartWMS.Common.Jwt
{
    /// <summary>
    ///  iss(Issuser)：JWT的签发主体；
    ///  sub(Subject)：JWT的主体，即它的所有人
    ///  aud(Audience)：JWT的接收对象
    ///  exp(Expiration time)：时间戳，JWT的过期时间
    ///  nbf(Not Before)：时间戳，JWT生效的开始时间
    ///  iat(Issued at)：时间戳，JWT的签发时间
    ///  jti(JWT ID)：JWT的唯一标识
    ///   </summary>
    public class JwtHelper
    {
        /// <summary>
        /// 创建Token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string CreateClaims(Staff user)
        {
            //创建用户身份标识  --声明 
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat,$"{ DateTimeOffset.Now.ToUnixTimeSeconds()}") ,
                new Claim(JwtRegisteredClaimNames.Nbf,$"{DateTimeOffset.Now.ToUnixTimeSeconds()}") ,
                new Claim(JwtRegisteredClaimNames.Exp,$"{ DateTimeOffset.Now.AddMinutes(36000).ToUnixTimeSeconds()}")
            };

            //创建令牌
            var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtSecret.GetAccountKey()));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //载荷+安全算法+私钥
            var securityToken = new JwtSecurityToken(signingCredentials: creds, claims: claims);

            string jwtToken = new JwtSecurityTokenHandler().WriteToken(securityToken);
            return jwtToken;
        }
    }
}
